#include "STM32_Flush.h"

// addr: 页首地址
void erasePage(uint32_t addr) {
    FLASH_Unlock();					//解锁
    FLASH_ErasePage(addr);			//页擦除
    FLASH_Lock();					//加锁
}

// addr: 页首地址
// data: 存放在首地址的32位数据
void changeFlashFor32(uint32_t addr, uint32_t data) {
    FLASH_Unlock();							// 解锁
    FLASH_ProgramWord(addr, data);			// 32bits
    FLASH_Lock();							// 加锁
}

// addr: 页首地址
// data: 存放在首地址的16位数据
void changeFlashFor16(uint32_t addr, uint16_t data) {
    FLASH_Unlock();							// 解锁
    FLASH_ProgramHalfWord(addr, data);		// 16bits
    FLASH_Lock();							// 加锁
}

// 读取数据
void readFlash(uint32_t addr, char *buffer, int len) {
    for (int i = 0; i < len; i++) {
        buffer[i] = *(__IO uint8_t *)(addr + i);
    }
}

void Read_Flash_Code(void) {
    uint32_t address = 0x0800F000;
    int status = 0;
    char buffer[128] = {0};

    status = *((__IO uint32_t *)(address));	 // 读取 0x0800F000 处的32位值

    if (status != 0xFFFFFFFF) {		
        // 有内容
        int len = *((__IO uint32_t *)(address + 4));
        readFlash(address + 8, buffer, len);
        
        // 使用独立缓冲区拼接（解决覆盖问题）
		snprintf(buffer, sizeof(buffer), "%s\r\n", buffer);
		USART_SendString(&USART1_Cfg, (const unsigned char*)buffer, strlen(buffer));
		
		USART_printf(&USART1_Cfg, "[TEST]stm32flush.c line49\r\n");
		
    } else {
        // Flash无内容, 存入数据
        char *str = "!yang=12345678!";
        strncpy(buffer, str, strlen(str) + 1);
		buffer[sizeof(buffer) - 1] = '\0';  // 强制终止

        erasePage(address);
        changeFlashFor32(address, 14);
        changeFlashFor32(address + 4, strlen(buffer));

        for (int i = 0; i < sizeof(buffer); i += 4) {
            changeFlashFor32(address + 8 + i, *(int *)(buffer + i));
        }

		USART_printf(&USART1_Cfg, "write \r\n");
    }
}
